
package it.csttech.date;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.ext.ParamConverter;

import org.apache.commons.validator.routines.DateValidator;

/**
 * OVERVIEW This class provides a converter for dates
 * 
 * @author marcello.felappi
 * @author marco.dalena
 */
public class DateParamConverter implements ParamConverter<Date> {

	/**
	 * Object representing the request from the client
	 */
	private HttpServletRequest request;

	/**
	 * This method represents a constructor for the DateParamConverter class
	 * 
	 * @param request
	 */
	public DateParamConverter(HttpServletRequest request) {

		this.request = request;
	}

	/**
	 * Method used to transform a date in a string
	 * 
	 * @param date
	 *            - date parameter
	 * @return the string converted from the date input
	 */
	@Override
	public String toString(Date date) {

		Locale locale = request.getLocale();
		DateFormat format =
			SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT, locale);
		return format.format(date);
	}

	/**
	 * Method used to translate the string parameter in a date according to the
	 * locale of the request
	 * 
	 * @param input
	 *            - string representing the parameter value
	 * @throws IllegalArgumentException
	 *             - thrown because of an error parsing the date
	 * @return the date converted from the string input according to the locale
	 *         of the request
	 */
	@Override
	public Date fromString(String input) {

		System.out.println("date converter before setting locale, string is " +
			input);
		Locale locale = request.getLocale();
		System.out.println("locale is " + locale);
		DateFormat format =
			SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT, locale);
		try {
			System.out.println("date converter before validation");
			DateValidator validator = new DateValidator();
			if (validator.validate(
				input, ((SimpleDateFormat) format).toPattern(), locale) != null) {
				Date date = format.parse(input);
				System.out.println("date converter inside if");
				return date;
			}
			else
				throw new IllegalArgumentException(
					Messages.getString("ErrorCode.wrongDateFormat"));
		}
		catch (ParseException e) {
			throw new IllegalArgumentException(
				Messages.getString("ErrorCode.wrongDateFormat"));
		}
	}

}
